<template>
  <div class="customer-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>客户管理</h2>
      <el-button type="primary" @click="showAddDialog"> 添加客户 </el-button>
    </div>

    <!-- 搜索和筛选 -->
    <SearchCard
      :default-values="{ search: '', status: '' }"
      @search="handleSearch"
      @reset="handleReset"
    >
      <template #default="{ searchForm }">
        <el-form-item label="搜索">
          <el-input
            v-model="searchForm.search"
            placeholder="姓名/别名/手机号/微信号"
            clearable
            @keyup.enter="handleSearch"
            style="width: 240px"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="全部状态"
            clearable
            style="width: 120px"
          >
            <el-option
              v-for="(config, key) in CUSTOMER_STATUS"
              :key="key"
              :label="config.label"
              :value="key"
            />
          </el-select>
        </el-form-item>
      </template>
    </SearchCard>

    <!-- 客户列表 -->
    <DataTable
      title="��户列表"
      :data="customers"
      :loading="loading"
      :total="pagination.total"
      :current-page="pagination.page"
      :page-size="pagination.limit"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
      <el-table-column label="序号" width="60" align="center" fixed="left">
        <template #default="{ $index }">
          {{ (pagination.page - 1) * pagination.limit + $index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="name" label="姓名" min-width="100" />
      <el-table-column prop="alias" label="别名" min-width="100">
        <template #default="{ row }">
          {{ displayEmptyValue(row.alias) }}
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="手机号" min-width="120" />
      <el-table-column prop="wechat" label="微信号" min-width="100">
        <template #default="{ row }">
          {{ displayEmptyValue(row.wechat) }}
        </template>
      </el-table-column>
      <el-table-column label="剩余面单数量" width="120" align="center">
        <template #default="{ row }">
          <el-tag :type="getWaybillCountType(row.waybillStats?.remaining || 0)">
            {{ row.waybillStats?.remaining || 0 }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="身份证照片" min-width="120" align="center">
        <template #default="{ row }">
          <div class="id-card-photos">
            <el-image
              v-if="row.idCardFront"
              :src="getImageUrl(row.idCardFront)"
              :preview-src-list="[getImageUrl(row.idCardFront)]"
              fit="cover"
              class="id-card-image"
              preview-teleported
            >
              <template #error>
                <div class="image-error">失败</div>
              </template>
            </el-image>
            <div v-else class="no-image">未传</div>

            <el-image
              v-if="row.idCardBack"
              :src="getImageUrl(row.idCardBack)"
              :preview-src-list="[getImageUrl(row.idCardBack)]"
              fit="cover"
              class="id-card-image"
              preview-teleported
            >
              <template #error>
                <div class="image-error">失败</div>
              </template>
            </el-image>
            <div v-else class="no-image">未传</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="80" align="center">
        <template #default="{ row }">
          <el-tag :type="getCustomerStatusConfig(row.status).type" size="small">
            {{ getCustomerStatusConfig(row.status).label }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right" align="center">
        <template #default="{ row }">
          <OperationButtons>
            <el-button type="primary" size="small" @click="showEditDialog(row)">
              编辑
            </el-button>
            <el-button type="info" size="small" @click="showDetailDialog(row)">
              详情
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </OperationButtons>
        </template>
      </el-table-column>
    </DataTable>

    <!-- 添加/编辑客户对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="700px"
      @close="resetForm"
    >
      <el-form
        ref="customerFormRef"
        :model="customerForm"
        :rules="VALIDATION_RULES"
        label-width="120px"
      >
        <!-- 基本信息 -->
        <div class="form-section">
          <div class="section-title">基本信息</div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="姓名" prop="name">
                <el-input
                  v-model="customerForm.name"
                  placeholder="请输入真实姓名"
                  maxlength="50"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="别名" prop="alias">
                <el-input
                  v-model="customerForm.alias"
                  placeholder="请输入别名（可选）"
                  maxlength="50"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="手机号" prop="phone">
                <el-input
                  v-model="customerForm.phone"
                  placeholder="请输入手机号"
                  maxlength="11"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="微信号" prop="wechat">
                <el-input
                  v-model="customerForm.wechat"
                  placeholder="请输入微信号"
                  maxlength="50"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="面单预充金额" prop="prepaidAmount">
                <el-input-number
                  v-model="customerForm.prepaidAmount"
                  :min="0"
                  :precision="2"
                  placeholder="请输入面单预充金额"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态">
                <el-radio-group v-model="customerForm.status">
                  <el-radio
                    v-for="(config, key) in CUSTOMER_STATUS"
                    :key="key"
                    :value="key"
                  >
                    {{ config.label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 交易方式 -->
        <div class="form-section">
          <div class="section-title">交易方式</div>
          <div class="transaction-methods">
            <div
              v-for="(method, index) in customerForm.transactionMethods"
              :key="index"
              class="transaction-method-item"
            >
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-select v-model="method.type" placeholder="选择交易方式">
                    <el-option
                      v-for="(label, key) in PAYMENT_METHODS"
                      :key="key"
                      :label="label"
                      :value="key"
                    />
                  </el-select>
                </el-col>
                <el-col :span="12">
                  <el-input
                    v-model="method.account"
                    placeholder="请输入交易账号"
                  />
                </el-col>
                <el-col :span="4">
                  <el-button
                    type="danger"
                    size="small"
                    @click="removeTransactionMethod(index)"
                    >删除</el-button
                  >
                </el-col>
              </el-row>
            </div>
            <el-button type="primary" size="small" @click="addTransactionMethod"
              >添加交易方式</el-button
            >
          </div>
        </div>

        <!-- 发货地址 -->
        <div class="form-section">
          <div class="section-title">发货地址</div>
          <div class="shipping-addresses">
            <div
              v-for="(address, index) in customerForm.shippingAddresses"
              :key="index"
              class="address-item"
            >
              <el-row :gutter="20">
                <el-col :span="20">
                  <el-input
                    v-model="customerForm.shippingAddresses[index]"
                    placeholder="请输入发货地址"
                  />
                </el-col>
                <el-col :span="4">
                  <el-button
                    type="danger"
                    size="small"
                    @click="removeShippingAddress(index)"
                    >删除</el-button
                  >
                </el-col>
              </el-row>
            </div>
            <el-button type="primary" size="small" @click="addShippingAddress"
              >添加发货地址</el-button
            >
          </div>
        </div>

        <!-- 身份证照片 -->
        <div class="form-section">
          <div class="section-title">身份证照片</div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="身份证正面">
                <div class="id-card-upload">
                  <div
                    v-if="customerForm.idCardFront"
                    class="id-card-preview-container"
                  >
                    <el-image
                      :src="getImageUrl(customerForm.idCardFront)"
                      fit="cover"
                      class="id-card-preview-image"
                    />
                    <div class="id-card-actions">
                      <el-button
                        type="primary"
                        size="small"
                        @click="handleReplaceImage('front')"
                      >
                        更换图片
                      </el-button>
                      <el-button
                        type="danger"
                        size="small"
                        @click="handleRemoveImage('front')"
                      >
                        删除
                      </el-button>
                    </div>
                  </div>

                  <ImageUpload
                    v-else
                    v-model="customerForm.idCardFront"
                    tip="请上传身份证正面照片"
                  />
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="身份证反面">
                <div class="id-card-upload">
                  <div
                    v-if="customerForm.idCardBack"
                    class="id-card-preview-container"
                  >
                    <el-image
                      :src="getImageUrl(customerForm.idCardBack)"
                      fit="cover"
                      class="id-card-preview-image"
                    />
                    <div class="id-card-actions">
                      <el-button
                        type="primary"
                        size="small"
                        @click="handleReplaceImage('back')"
                      >
                        更换图片
                      </el-button>
                      <el-button
                        type="danger"
                        size="small"
                        @click="handleRemoveImage('back')"
                      >
                        删除
                      </el-button>
                    </div>
                  </div>

                  <ImageUpload
                    v-else
                    v-model="customerForm.idCardBack"
                    tip="请上传身份证反面照片"
                  />
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          :loading="submitLoading"
          @click="handleSubmit"
        >
          {{ isEdit ? "更新" : "创建" }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 客户详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="客户详情" width="800px">
      <el-descriptions :column="2" border v-if="currentCustomer">
        <el-descriptions-item label="姓名">{{
          currentCustomer.name
        }}</el-descriptions-item>
        <el-descriptions-item label="别名">{{
          displayEmptyValue(currentCustomer.alias)
        }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{
          currentCustomer.phone
        }}</el-descriptions-item>
        <el-descriptions-item label="微信号">{{
          displayEmptyValue(currentCustomer.wechat)
        }}</el-descriptions-item>
        <el-descriptions-item label="面单预充金额"
          >{{ currentCustomer.prepaidAmount || 0 }} 元</el-descriptions-item
        >
        <el-descriptions-item label="剩余面单数量">{{
          currentCustomer.waybillStats?.remaining || 0
        }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getCustomerStatusConfig(currentCustomer.status).type">
            {{ getCustomerStatusConfig(currentCustomer.status).label }}
          </el-tag>
        </el-descriptions-item>

        <el-descriptions-item label="交易方式" :span="2">
          <div
            v-if="
              currentCustomer.transactionMethods &&
              currentCustomer.transactionMethods.length > 0
            "
          >
            <el-tag
              v-for="(method, index) in currentCustomer.transactionMethods"
              :key="index"
              class="method-tag"
            >
              {{ getPaymentMethodLabel(method.type) }}: {{ method.account }}
            </el-tag>
          </div>
          <span v-else>-</span>
        </el-descriptions-item>

        <el-descriptions-item label="发货地址" :span="2">
          <div
            v-if="
              currentCustomer.shippingAddresses &&
              currentCustomer.shippingAddresses.length > 0
            "
          >
            <div
              v-for="(address, index) in currentCustomer.shippingAddresses"
              :key="index"
              class="address-item"
            >
              {{ index + 1 }}. {{ address }}
            </div>
          </div>
          <span v-else>-</span>
        </el-descriptions-item>

        <el-descriptions-item label="身份证正面">
          <el-image
            v-if="currentCustomer.idCardFront"
            :src="getImageUrl(currentCustomer.idCardFront)"
            :preview-src-list="[getImageUrl(currentCustomer.idCardFront)]"
            fit="cover"
            style="width: 200px; height: 120px; border-radius: 4px"
            preview-teleported
          />
          <span v-else>未上传</span>
        </el-descriptions-item>
        <el-descriptions-item label="身份证反面">
          <el-image
            v-if="currentCustomer.idCardBack"
            :src="getImageUrl(currentCustomer.idCardBack)"
            :preview-src-list="[getImageUrl(currentCustomer.idCardBack)]"
            fit="cover"
            style="width: 200px; height: 120px; border-radius: 4px"
            preview-teleported
          />
          <span v-else>未上传</span>
        </el-descriptions-item>

        <el-descriptions-item label="创建时间" :span="2">
          {{ formatDate(currentCustomer.createdAt) }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 更换图片对话框 -->
    <el-dialog
      v-model="replaceImageDialogVisible"
      title="更换图片"
      width="500px"
    >
      <ImageUpload
        v-model="tempImageUrl"
        :tip="`请上传身份证${
          replaceImageType === 'front' ? '正面' : '反面'
        }照片`"
      />
      <template #footer>
        <el-button @click="replaceImageDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmReplaceImage"
          >确认更换</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search } from "@element-plus/icons-vue";
import api from "@/utils/api";
import ImageUpload from "@/components/ImageUpload.vue";
import DataTable from "@/components/DataTable.vue";
import SearchCard from "@/components/SearchCard.vue";
import OperationButtons from "@/components/OperationButtons.vue";
import { getBatchCustomerWaybillStats } from "@/services/waybillService";
import {
  CUSTOMER_STATUS,
  PAYMENT_METHODS,
  VALIDATION_RULES,
} from "@/utils/constants";
import {
  getCustomerStatusConfig,
  getPaymentMethodLabel,
  formatDate,
  getImageUrl,
  displayEmptyValue,
} from "@/utils/helpers";

// 响应式数据
const loading = ref(false);
const submitLoading = ref(false);
const customers = ref([]);
const dialogVisible = ref(false);
const detailDialogVisible = ref(false);
const isEdit = ref(false);
const currentCustomer = ref(null);
const customerFormRef = ref();

// 图片替换相关
const replaceImageDialogVisible = ref(false);
const replaceImageType = ref("front");
const tempImageUrl = ref("");

// 分页数据
const pagination = reactive({
  page: 1,
  limit: 10,
  total: 0,
});

// 客户表单
const customerForm = reactive({
  name: "",
  alias: "",
  phone: "",
  wechat: "",
  prepaidAmount: 0,
  transactionMethods: [],
  shippingAddresses: [],
  idCardFront: "",
  idCardBack: "",
  status: "active",
});

// 计算属性
const dialogTitle = computed(() => (isEdit.value ? "编辑客户" : "添加客户"));

// 获取面单数量标签类型
const getWaybillCountType = (count) => {
  if (count === 0) return "danger";
  if (count < 10) return "warning";
  return "success";
};

// 添加交易方式
const addTransactionMethod = () => {
  customerForm.transactionMethods.push({ type: "", account: "" });
};

// 删除交易方式
const removeTransactionMethod = (index) => {
  customerForm.transactionMethods.splice(index, 1);
};

// 添加发货地址
const addShippingAddress = () => {
  customerForm.shippingAddresses.push("");
};

// 删除发货地址
const removeShippingAddress = (index) => {
  customerForm.shippingAddresses.splice(index, 1);
};

// 获取客户列表
const fetchCustomers = async () => {
  loading.value = true;
  try {
    const params = {
      page: pagination.page,
      limit: pagination.limit,
      search: searchForm?.search || "",
      status: searchForm?.status || "",
    };

    const response = await api.get("/customers", { params });
    customers.value = response.data.customers;
    pagination.total = response.data.total;

    // 批量获取面单统计
    if (customers.value.length > 0) {
      const customerIds = customers.value.map((c) => c._id);
      const waybillStats = await getBatchCustomerWaybillStats(customerIds);

      customers.value.forEach((customer) => {
        customer.waybillStats = waybillStats[customer._id] || { remaining: 0 };
      });
    }
  } catch (error) {
    ElMessage.error("获取客户列表失败");
  } finally {
    loading.value = false;
  }
};

let searchForm = null;

// 搜索
const handleSearch = (form) => {
  searchForm = form;
  pagination.page = 1;
  fetchCustomers();
};

// 重置搜索
const handleReset = (form) => {
  searchForm = form;
  pagination.page = 1;
  fetchCustomers();
};

// 分页处理
const handleSizeChange = (size) => {
  pagination.limit = size;
  pagination.page = 1;
  fetchCustomers();
};

const handleCurrentChange = (page) => {
  pagination.page = page;
  fetchCustomers();
};

// 显示添加对话框
const showAddDialog = () => {
  isEdit.value = false;
  resetForm();
  dialogVisible.value = true;
};

// 显示编辑对话框
const showEditDialog = (customer) => {
  isEdit.value = true;
  currentCustomer.value = customer;
  Object.assign(customerForm, {
    ...customer,
    transactionMethods: customer.transactionMethods || [],
    shippingAddresses: customer.shippingAddresses || [],
    prepaidAmount: customer.prepaidAmount || 0,
  });
  dialogVisible.value = true;
};

// 显示详情对话框
const showDetailDialog = (customer) => {
  currentCustomer.value = customer;
  detailDialogVisible.value = true;
};

// 重置表单
const resetForm = () => {
  Object.assign(customerForm, {
    name: "",
    alias: "",
    phone: "",
    wechat: "",
    prepaidAmount: 0,
    transactionMethods: [],
    shippingAddresses: [],
    idCardFront: "",
    idCardBack: "",
    status: "active",
  });
  customerFormRef.value?.resetFields();
  customerFormRef.value?.clearValidate();
};

// 提交表单
const handleSubmit = async () => {
  if (!customerFormRef.value) return;

  try {
    const valid = await customerFormRef.value.validate();
    if (!valid) return;
  } catch {
    return;
  }

  submitLoading.value = true;

  try {
    if (isEdit.value) {
      await api.put(`/customers/${currentCustomer.value._id}`, customerForm);
      ElMessage.success("客户更新成功");
    } else {
      await api.post("/customers", customerForm);
      ElMessage.success("客户创建成功");
    }

    dialogVisible.value = false;
    fetchCustomers();
  } catch (error) {
    ElMessage.error(error.response?.data?.error || "操作失败");
  } finally {
    submitLoading.value = false;
  }
};

// 删除客户
const handleDelete = async (customer) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除客户 "${customer.name}" 吗？`,
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    await api.delete(`/customers/${customer._id}`);
    ElMessage.success("客户删除成功");
    fetchCustomers();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除失败");
    }
  }
};

// 处理更换图片
const handleReplaceImage = (type) => {
  replaceImageType.value = type;
  tempImageUrl.value = "";
  replaceImageDialogVisible.value = true;
};

// 确认更换图片
const confirmReplaceImage = () => {
  if (!tempImageUrl.value) {
    ElMessage.warning("请先上传新图片");
    return;
  }

  if (replaceImageType.value === "front") {
    customerForm.idCardFront = tempImageUrl.value;
  } else {
    customerForm.idCardBack = tempImageUrl.value;
  }

  replaceImageDialogVisible.value = false;
  ElMessage.success("图片更换成功");
};

// 删除图片
const handleRemoveImage = (type) => {
  if (type === "front") {
    customerForm.idCardFront = "";
  } else {
    customerForm.idCardBack = "";
  }
  ElMessage.success("图片已删除");
};

// 组件挂载时获取数据
onMounted(() => {
  fetchCustomers();
});
</script>

<style lang="scss" scoped>
.customer-management {
  height: 100%;
  display: flex;
  flex-direction: column;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      margin: 0;
      color: $text-primary;
      font-size: 20px;
      font-weight: 600;
    }
  }

  .form-section {
    margin-bottom: 24px;

    .section-title {
      font-size: 14px;
      font-weight: 600;
      color: $text-primary;
      margin-bottom: 16px;
      padding-bottom: 8px;
      border-bottom: 1px solid $border-color;
    }
  }

  .transaction-methods,
  .shipping-addresses {
    .transaction-method-item,
    .address-item {
      margin-bottom: 12px;
    }
  }

  .method-tag {
    margin-right: 8px;
    margin-bottom: 4px;
  }

  .address-item {
    margin-bottom: 4px;
  }

  .id-card-photos {
    display: flex;
    gap: 4px;
    align-items: center;
    justify-content: center;

    .id-card-image {
      width: 50px;
      height: 32px;
      border-radius: 4px;
      object-fit: cover;
    }

    .no-image {
      color: $text-secondary;
      font-size: 10px;
      width: 50px;
      height: 32px;
      display: flex;
      align-items: center;
      justify-content: center;
      border: 1px dashed #ddd;
      border-radius: 4px;
      background: #fafafa;
    }

    .image-error {
      font-size: 10px;
      color: $danger-color;
      width: 50px;
      height: 32px;
      display: flex;
      align-items: center;
      justify-content: center;
      border: 1px dashed #ddd;
      border-radius: 4px;
      background: #fafafa;
    }
  }

  .id-card-upload {
    .id-card-preview-container {
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 10px;

      .id-card-preview-image {
        width: 180px;
        height: 110px;
        border-radius: 4px;
        object-fit: cover;
        border: 1px solid #e0e0e0;
      }

      .id-card-actions {
        display: flex;
        gap: 10px;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .customer-management {
    .page-header {
      flex-direction: column;
      gap: 16px;
      align-items: stretch;
    }

    .id-card-photos {
      flex-direction: column;
      gap: 2px;
    }
  }
}
</style>
